package com.eln.medplayer;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Base64;

/**
 * Movie file meta data.
 * 
 * @author Josh
 */
public class Movie implements Parcelable
{
	
	private static final String MEDIA_ARTWORK_PATH = new String("/storage/sdcard0/artwork");
/** Movie title */
private final String title;

/** Movie file */
private final String moviePath;

/** MIME type */
private final String mimeType;

/** Movie duration in ms */
private final long duration;

/** Thumbnail file */
private final String thumbnailPath;

private final String albumId;

private String thumbstring;

private Bitmap thumbnail;

//private int bytlength;

/**
 * Constructor.
 * 
 * @param mediaCursor media cursor.
 * @param thumbnailCursor thumbnail cursor.
 */
public Movie(Cursor mediaCursor, Cursor thumbnailCursor,String AlbumId,ArrayList<listNames> nameList)
{
	 
    

    moviePath = mediaCursor.getString(mediaCursor.getColumnIndex(
            MediaStore.Video.Media.DATA));
    
    File file = new File(moviePath);
    Map<String,listNames> nms = new HashMap<String,listNames>();
    for( listNames nm : nameList ) {
        nms.put( nm.name, nm );
    };
    String clrname=clearedFilename(file.getName());
    listNames nm = nms.get( clrname );
    if (nm!=null){
    title =nm.title;
    }else{
    	title=file.getName();// file.getName();//mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(
    }
            //MediaStore.Video.Media.TITLE));

    mimeType = mediaCursor.getString(mediaCursor.getColumnIndex(
            MediaStore.Video.Media.MIME_TYPE));

    duration = mediaCursor.getLong(mediaCursor.getColumnIndex(
            MediaStore.Video.Media.DURATION));

   // if ( (thumbnailCursor != null) && thumbnailCursor.moveToFirst() )
   // {
    	String res=file.getName();
        int pos = res.lastIndexOf(".");
        if (pos > -1) res=res.substring(0, pos);
        res=res.replace("_LT","");
        res=res.replace("_EN","");
        thumbnailPath = MEDIA_ARTWORK_PATH+"/"+res+".jpg";//thumbnailCursor.getString(
                //thumbnailCursor.getColumnIndex(
                        //MediaStore.Video.Thumbnails.DATA));
   // }
   // else
    //{
    //    thumbnailPath = null;
    //}
        if (!moviePath.contains("mp3"))//((movie.getThumbnailPath() != null) || (movie.getAlbumId() == null))
        {
        	String fname=moviePath;
        	thumbnail =Bitmap.createScaledBitmap(getFrameFromVideo(fname),128, 75, true);// 256, 150, true);
        	//ByteArrayOutputStream bs = new ByteArrayOutputStream();
     		//thumbnail.compress(Bitmap.CompressFormat.WEBP, 10, bs);
     		//byte[] _byte=bs.toByteArray();
     		//thumbnail=BitmapFactory.decodeByteArray(_byte, 0,_byte.length);
        }
        else
        {
    		String thpath=thumbnailPath;
    		Uri uri=Uri.parse(thpath);
     		Bitmap bitmap=drawableToBitmap(Drawable.createFromPath(thpath));
     		thumbnail = Bitmap.createScaledBitmap(bitmap,128, 75, true);// 256, 150, true);	
     		//ByteArrayOutputStream bs = new ByteArrayOutputStream();
     		//thumbnail.compress(Bitmap.CompressFormat.WEBP, 10, bs);
     		//byte[] _byte=bs.toByteArray();
     		//thumbnail=BitmapFactory.decodeByteArray(_byte, 0,_byte.length);
        }
    
    if (AlbumId != null)
    {
    	albumId = AlbumId;
    }
    else
    {
    	albumId = null;
    }
}

public static Bitmap drawableToBitmap (Drawable drawable) {
	 
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

private Bitmap getFrameFromVideo(String name){
	//File sdcard =  new File(MEDIA_VIDEO_PATH);
	//File file = new File(sdcard, name);
	File file = new File(name);
	Bitmap res=null;
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    try {
        retriever.setDataSource(file.getAbsolutePath());

        res=retriever.getFrameAtTime(5000000,MediaMetadataRetriever.OPTION_CLOSEST);


    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
        }
    }
    return res;
}

public String clearedFilename(String filename){
	String res=filename;
  int pos = res.lastIndexOf(".");
  if (pos > -1) res=res.substring(0, pos);
  res=res.replace("_LT","");
  res=res.replace("_EN","");
  //pos = res.lastIndexOf("_");
  //if (pos > -1) res=res.substring(pos+1, res.length());
	return res;
}

public String BitMapToString(Bitmap bitmap){
    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] arr=baos.toByteArray();
    String result=Base64.encodeToString(arr, Base64.DEFAULT);
    return result;
}

public Bitmap StringToBitMap(String image){
try{
   byte [] encodeByte=Base64.decode(image,Base64.DEFAULT);
   Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
   return bitmap;
 }catch(Exception e){
   e.getMessage();
  return null;
 }
}

public Movie(Parcel in)
{
	//thumbnail = (Bitmap)in.readParcelable(getClass().getClassLoader());
	//thumbnail= Bitmap.CREATOR.createFromParcel(in);
    title = in.readString();
    moviePath = in.readString();
    mimeType = in.readString();
    duration = in.readLong();
    thumbnailPath = in.readString();
   	albumId = in.readString();
  // 	thumbstring=in.readString();
   //	if(thumbstring!=null){
   	//try{
   	//thumbnail=StringToBitMap(thumbstring);
   	//}catch(Exception ex){thumbnail=null;}
   	//}
   //	thumbnail=(Bitmap)in.readParcelable(getClass().getClassLoader());
   //	thumbnail= in.readParcelable(Bitmap.class.getClassLoader());
   //	bytlength=in.readInt();
    //byte[] _byte = new byte[bytlength]; 
    //in.readByteArray(_byte);
   	//thumbnail= BitmapFactory.decodeByteArray(_byte, 0,bytlength);
   	//in.setDataPosition(0);
   	
}
/**
 * Get the movie title.
 * 
 * @return movie title.
 */
public String getTitle() {
    return title;
}

/**
 * Get the movie path.
 * 
 * @return movie path.
 */
public String getMoviePath() {
    return moviePath;
}

/**
 * Get the MIME type.
 * 
 * @return MIME type.
 */
public String getMimeType() {
    return mimeType;
}

/**
 * Get the movie duration.
 * 
 * @return movie duration.
 */
public long getDuration() {
    return duration;
}

/**
 * Get the thumbnail path.
 * 
 * @return thumbnail path.
 */
public String getThumbnailPath() {
    return thumbnailPath;
}

public String getAlbumId() {
    return albumId;
}

public Bitmap getThumbnail() {
    return thumbnail;
}

/*
 * @see java.lang.Object#toString()
 */
@Override
public String toString()
{
    return "Movie [title=" + title + ", moviePath=" + moviePath
            + ", mimeType=" + mimeType + ", duration=" + duration
            + ", thumbnailPath=" + thumbnailPath + "]";
}

public static final Parcelable.Creator<Movie> CREATOR =
new Parcelable.Creator<Movie>() {

@Override
public Movie createFromParcel(Parcel source) {
  return new Movie(source);
}

@Override
public Movie[] newArray(int size) {
return new Movie[size];
}

};

@Override
public int describeContents() {
	// TODO Auto-generated method stub
	return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
	// TODO Auto-generated method stub
	//dest.setDataPosition(0);
	//thumbnail.writeToParcel(dest, 0);
	dest.writeString(title);
	dest.writeString(moviePath);
	dest.writeString(mimeType);
	dest.writeLong(duration);
	dest.writeString(thumbnailPath);
	dest.writeString(albumId);
	//dest.writeParcelable(thumbnail, 0);
	//if (thumbnail!=null){
	//	try{
	//		thumbstring=BitMapToString(thumbnail);
	//	}catch(Exception ex){thumbstring=null;}
	//}
	//thumbstring=BitMapToString(thumbnail);
		
	//thumbstring=null;
	//dest.writeString(thumbstring);
	//dest.writeValue(thumbnail);
	//ByteArrayOutputStream bs = new ByteArrayOutputStream();
    //thumbnail.compress(Bitmap.CompressFormat.PNG, 50, bs);
    //byte[] _byte=bs.toByteArray();
	//dest.writeInt(_byte.length); 
	//dest.writeByteArray(_byte); 
}

}
